import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';

export default class TInputSearchComponent extends Component {
  @service call;

  @tracked err = false;
  @tracked showSearch = false;
  @tracked inputSearchValue = this.args.value || '';
  @tracked inputSearchValuestr = '';
  @tracked inputSearchText = '';
  @tracked items;

  constructor() {
    super(...arguments);
    this.loadItems();
    // 如果是选择模式且有初始值，设置显示文本
    if (this.args.selectMode && this.args.value && this.args.options) {
      const option = this.args.options.find(opt => opt.id === this.args.value);
      if (option) {
        this.inputSearchText = option.name;
        this.inputSearchValuestr = option.name;
      }
    }
  }

  // 获取清除选项
  get clearOption() {
    return { id: '', name: this.args.clearText || '全部' };
  }

  // 获取placeholder文本
  get placeholderText() {
    if (this.args.placeholder) {
      return `${this.args.placeholder}...`;
    }
    return `请输入${this.args.key}`;
  }

  // 获取过滤后的项目列表
  get filteredItems() {
    if (!this.items) return [];
    
    if (!this.inputSearchText.trim()) {
      return this.items;
    }
    
    const searchTerm = this.inputSearchText.toLowerCase();
    return this.items.filter(item =>
      item.name?.toLowerCase().includes(searchTerm)
    );
  }

  loadItems(searchInput) {
    // 如果提供了options参数，直接使用options
    if (this.args.options) {
      this.items = this.args.options;
      // 过滤搜索结果
      if (searchInput) {
        this.items = this.items.filter(
          (item) => item.name.indexOf(searchInput) !== -1,
        );
      }
      return;
    }
    
    // 否则使用原有的API调用方式
    if (this.args.searchKey == undefined || this.args.searchKey == '') {
      return;
    }
    this.call.getCached('/api/config/' + this.args.searchKey).then((res) => {
      if (res.success) {
        this.items = JSON.parse(res.data.value);

        // 过滤搜索结果
        if (searchInput) {
          this.items = this.items.filter(
            (item) => item.name.indexOf(searchInput) !== -1,
          );
        }
      }
    });
  }

  @action
  startSearch($event) {
    if (!this.showSearch) {
      this.showSearch = true;
    }
    this.loadItems($event.target.value);
  }

  @action
  directSearch() {
    if (!this.showSearch) {
      this.showSearch = true;
    }
    this.loadItems('');
  }

  @action
  closeSearch($event) {
    const searchInput = $event.target.value;
    if (
      this.inputSearchValuestr != undefined &&
      searchInput != this.inputSearchValuestr
    ) {
      this.inputSearchText = this.inputSearchValuestr;
    }
    setTimeout(() => {
      this.showSearch = false;
      this.checkRequired();
    }, 300);
  }

  @action
  checkRequired() {
    if (this.args.selectMode) {
      this.err = this.args.required && this.inputSearchValue.trim() === '';
    } else {
      this.err = this.args.required && this.inputSearchText.trim() === '';
    }
  }

  @action
  selectOne(item) {
    this.showSearch = false;
    if (this.inputSearchValue == item.id) {
      return;
    }

    // 如果是清除选项（空id），清空输入文本
    if (item.id === '') {
      this.inputSearchText = '';
      this.inputSearchValuestr = '';
    } else {
      this.inputSearchText = item.name;
      this.inputSearchValuestr = item.name;
    }
    
    this.inputSearchValue = item.id;

    if (this.args.cb) {
      this.args.cb(item);
    }
    
    // 如果是选择模式且有onChange回调，触发onChange
    if (this.args.selectMode && this.args.onChange) {
      this.args.onChange(item.id);
    }
  }
}
